package com.tanhua.service;

import cn.hutool.core.collection.CollUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.exception.BusinessException;
import com.tanhua.interceptor.UserHolder;
import model.domain.UserInfo;
import model.mongo.Video;
import model.vo.ErrorResult;
import model.vo.PageResult;
import model.vo.VideoVo;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class SmallVideosService {
    @Autowired
    private FdfsWebServer webServer;

    @DubboReference
    private VideoApi videoApi;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @DubboReference
    private UserInfoApi userInfoApi;

    public void saveVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        String filename = videoFile.getOriginalFilename();
        filename = filename.substring(filename.lastIndexOf(".") + 1);

        StorePath storePath = fastFileStorageClient.uploadFile(
                videoFile.getInputStream(),
                videoFile.getSize(),
                filename,
                null);
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();

        String imageUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());

        Video video = new Video().setUserId(UserHolder.getUserId())
                .setPicUrl(imageUrl)
                .setVideoUrl(videoUrl)
                .setText("我就是我，不一样的烟火");
        String videoId = videoApi.save(video);
        if (StringUtils.isEmpty(videoId)) {
            throw new BusinessException(ErrorResult.error());
        }
    }

    public PageResult queryVideoList(Integer page, Integer pageSize) {
        String redisKey = Constants.VIDEOS_RECOMMEND + UserHolder.getUserId();
        String redisValue = redisTemplate.opsForValue().get(redisKey);

        List<Video> videos = new ArrayList<>();
        int redisPages = 0;
        if (!StringUtils.isEmpty(redisValue)) {
            String[] values = redisValue.split(",");
            if ((page - 1) * pageSize < values.length) {
                List<Long> vids = Arrays.stream(values)
                        .skip((page - 1) * pageSize)
                        .limit(pageSize)
                        .map(a -> Long.valueOf(a))
                        .collect(Collectors.toList());
                videos = videoApi.findMovementsByVids(vids);
            }
        }

        if (videos.isEmpty()) {
            videos = videoApi.queryVideoList(page - redisPages, pageSize);
        }
        List<Long> userIds = CollUtil.getFieldValues(videos, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);

        ArrayList<VideoVo> videoVos = new ArrayList<>();
        for (Video video : videos) {
            UserInfo userInfo = map.get(video.getUserId());
            if (userInfo != null) {
                VideoVo videoVo = VideoVo.init(userInfo, video);
                videoVos.add(videoVo);
            }
        }
        return new PageResult(page, pageSize, 0L, videoVos);
    }
}
